package com.yc.config;

import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Properties;

public class NacosWritableDataSourceJackson<T> implements WritableDataSource<List<T>> {

    private final ConfigService configService;
    private final String dataId;
    private final String groupId;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public NacosWritableDataSourceJackson(String serverAddr, String username, String password, String namespace,
                                          String dataId, String groupId) throws Exception {
        this.dataId = dataId;
        this.groupId = groupId;

        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr);
        properties.setProperty(PropertyKeyConst.USERNAME, username);
        properties.setProperty(PropertyKeyConst.PASSWORD, password);
        properties.setProperty(PropertyKeyConst.NAMESPACE, namespace);

        this.configService = NacosFactory.createConfigService(properties);
    }

    @Override
    public void write(List<T> rules) throws Exception {
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rules);
        configService.publishConfig(dataId, groupId, json);
    }

    @Override
    public void close() {
        // 资源清理（一般无须处理）
    }
}
